
<?php
$host = '0.0.0.0';
$port = 9999;
$listen_socket = socket_create( AF_INET, SOCK_STREAM, SOL_TCP );
socket_bind( $listen_socket, $host, $port );
socket_listen( $listen_socket );
while( true ){
    $connection_socket = socket_accept( $listen_socket );
    $pid = pcntl_fork();
    // 在子进程里处理业务逻辑
    if ( 0 == $pid ) {
        socket_recv( $connection_socket, $recv_content, 4, MSG_WAITALL );
        $body_len_pack = unpack( "Nlen", $recv_content );
        $body_len      = $body_len_pack['len'];
        socket_recv( $connection_socket, $recv_content, $body_len, MSG_WAITALL );
        echo "从客户端收到：{$recv_content}".PHP_EOL;
        // 模拟5秒钟的业务逻辑处理
        sleep( 5 );
        $msg = "helloworld\r\n";
        socket_write( $connection_socket, $msg, strlen( $msg ) );
        socket_close( $connection_socket );
    }
}
socket_close( $listen_socket );